package client;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import java.util.Date;

public class Client extends JFrame implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Socket socket;
	private JTextArea jta;
	private JTextArea jta1;
	private JButton send;
	private Object message;

	public Client() throws IOException {
		// TODO Auto-generated constructor stub
		setTitle("聊天器");
		setSize(600, 600);
		setResizable(false);
		Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension framesize = this.getSize();
		int x = (int) screensize.getWidth() / 2 - (int) framesize.getWidth() / 2;
		int y = (int) screensize.getHeight() / 2 - (int) framesize.getHeight() / 2;
		setLocation(x, y);
		setLayout(null);
		setVisible(true);

		jta = new JTextArea();
		jta.setBorder(BorderFactory.createLoweredBevelBorder());
		JScrollPane jsp = new JScrollPane(jta);
		jsp.setSize(565, 340);
		jsp.setLocation(10, 10);
		add(jsp);

		jta1 = new JTextArea();
		jta1.setBorder(BorderFactory.createLoweredBevelBorder());
		JScrollPane jsp1 = new JScrollPane(jta1);
		jsp1.setSize(565, 140);
		jsp1.setLocation(10, 360);
		add(jsp1);

		send = new JButton("Send");
		send.setBounds(380, 515, 80, 30);
		send.addActionListener(this);
		add(send);

		JButton clear = new JButton("Clear");
		clear.setBounds(480, 515, 80, 30);
		clear.addActionListener(this);
		add(clear);
		
		jta1.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub
				super.keyPressed(e);
				int code=e.getKeyCode();
				switch (code) {
				case KeyEvent.VK_ENTER:
					Date date=new Date();
		            DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		            String time=df.format(date);
		        	message=jta1.getText();
		        	jta.append("我（" + time + "）：\n" + message + "\n");
		        	send();
		        	jta1.setText("");
					break;
				default:
					break;
				}
			}
		});

		setDefaultCloseOperation(EXIT_ON_CLOSE);

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					send.setEnabled(false);
					socket=new Socket("192.168.1.100", 9966);
					jta.append("连接的服务器为：" + socket.getInetAddress().getHostAddress() + "\n");
					accept1();
					send.setEnabled(true);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					new Client();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
    
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
        String com=e.getActionCommand();
        if(com=="Send"){
        	Date date=new Date();
            DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time=df.format(date);
        	message=jta1.getText();
        	jta.append("我（" + time + "）：\n" + message + "\n");
        	send();
        	jta1.setText("");
        }
        
        if(com=="Clear"){
        	jta1.setText("");
        }
	}
    
	public void accept1(){
        new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					Object acmessage;
					try {
						ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
						acmessage=ois.readObject();
						Date date=new Date();
					    DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					    String time=df.format(date);
						jta.append(socket.getInetAddress().getHostAddress() + "（" + time + "）：\n" + acmessage + "\n");
					} catch (ClassNotFoundException | IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();	
    }
    
	public void send() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
				    oos.writeObject(message);
				    oos.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					System.out.println("服务器已经关闭！");
				}
				
			}
		}).start();
	}
}
